#include <func.h>

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int sockfd;
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    printf("sockfd=%d\n",sockfd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    ser.sin_port=htons(atoi(argv[2]));
    int ret;
    int reuse=1;
    ret=setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const void*)&reuse,sizeof(int));
    ret=bind(sockfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);
    int newfd;
    struct sockaddr_in cli;
    bzero(&cli,sizeof(cli));
    socklen_t len=sizeof(cli);
    char buf[1024]={0};
    int readynum;
    int epfd=epoll_create(6);
    struct epoll_event event,evlist[3];
    event.data.fd=STDIN_FILENO;
    event.events=EPOLLIN;
    ret=epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event); 
    ERROR_CHECK(ret,-1,"epoll_ctl");
    event.data.fd=sockfd;
    ret=epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event); 
    ERROR_CHECK(ret,-1,"epoll_ctl");
    int i;
    while(1)
    {
        readynum=epoll_wait(epfd,evlist,3,-1);
        printf("readynum=%d\n",readynum);
        for(i=0;i<readynum;++i)
        {
            if(evlist[i].data.fd==newfd)
            {
                bzero(buf,sizeof(buf));
                printf("i=%d\n",i);
                if(!recv(newfd,buf,sizeof(buf)-1,0))
                {
                    printf("GooBye!\n");
                    ret=epoll_ctl(epfd,EPOLL_CTL_DEL,newfd,&event);
                    ERROR_CHECK(ret,-1,"epoll_ctl");
                    break;
                }
                printf("strlen of buf = %ld\n",strlen(buf));
                write(STDOUT_FILENO,buf,strlen(buf));
            }
            if(evlist[i].data.fd==STDIN_FILENO)
            {
                bzero(buf,sizeof(buf));
                read(STDIN_FILENO,buf,sizeof(buf));
                send(newfd,buf,sizeof(buf)-1,0);
            }
            if(evlist[i].data.fd==sockfd)
            {
                bzero(&cli,sizeof(cli));
                newfd=accept(sockfd,(struct sockaddr*)&cli,&len);
                ERROR_CHECK(newfd,-1,"accept");
                event.data.fd=newfd;
                //event.events=EPOLLIN|EPOLLET;
                ret=epoll_ctl(epfd,EPOLL_CTL_ADD,newfd,&event); 
                ERROR_CHECK(ret,-1,"epoll_ctl");
                printf("client ip=%s,client port=%d\n",
                       inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
            }
        }}
    return 0;
}

